import router from './router'
import store from './store'
import storage from 'store'
import NProgress from 'nprogress' // progress bar
import '@/components/NProgress/nprogress.less' // progress bar custom style
import notification from 'ant-design-vue/es/notification'
import { setDocumentTitle, domTitle } from '@/utils/domUtil'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { i18nRender } from '@/locales'
import defaultSettings from '@/config/defaultSettings'


NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['login', 'register', 'registerResult'] // no redirect whitelist
const loginRoutePath = '/user/login'
const defaultRoutePath = '/dashboard/workplace'

router.beforeEach((to, from, next) => {
    //判断是否为跳转到外部链接
    if(to.meta && to.meta.extLink && to.meta.isNewWin=='1'){
        window.open(to.meta.extLink, "_blank");
        return false
      }
    NProgress.start() 
    if (to.query.token) {
        sessionStorage.setItem(ACCESS_TOKEN, to.query.token)
    }
    if (sessionStorage.getItem(ACCESS_TOKEN)) {

    ///为了防止点击返回回到上一页
    ///这行代码需要和App.vue 中的mounted 中监听返回事件一起使用
    // 这个暂时废弃
    // history.pushState(null, null, window.location.protocol+"//"+window.location.host+to.path)

    if (to.path === loginRoutePath) {
      next({ path: defaultRoutePath })
      NProgress.done()
    } else{
      if (store.getters.addRouters.length === 0) {
        // request login userInfo
        store.dispatch('GetInfo').then(res => {
            store.dispatch('GenerateRoutes', res.result).then(() => {
              // 根据roles权限生成可访问的路由表
              // 动态添加可访问路由表
              router.addRoutes(store.getters.addRouters)
              // 请求带有 redirect 重定向时，登录自动重定向到该地址
              const redirect = decodeURIComponent(from.query.redirect || to.path)
              if (to.path === redirect) {
                next({ ...to, replace: true })
              } else {
                // 跳转到目的路由
                next({ path: redirect })
              }
            })
          })
          .catch((res) => {
            NProgress.done()
            notification.error({ message: '系统提示', description:res.message})
            // 失败时，获取用户信息失败时，调用登出，来清空历史保留信息
            store.dispatch('Logout').then(() => {
              next({ path: loginRoutePath, query: { redirect: to.fullPath } })
            })
            
          })
      } else {
        //判断打开的tab页是否过多
        if(defaultSettings.maxTabCount>0 
            && store.state.tabPathList.fullPathList.length>=defaultSettings.maxTabCount
            && store.state.tabPathList.fullPathList.indexOf(to.fullPath) < 0){
            notification.warning({ message: '系统提示', description: '标签页达到最大上限，请先关闭一些',duration:2})
            return false;
        }
        next()
      }
    }
  } else {
    if (whiteList.includes(to.name)) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next({ path: loginRoutePath, query: { redirect: to.fullPath } })
      NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
    }
  }
})

router.afterEach(() => {
  NProgress.done() // finish progress bar
})

router.onError((callback)=>{
  notification.error({ message: '系统提示', description: '发生错误'+callback,duration:2})
  NProgress.done()
});